<%@ page import="com.deepai.dprsmgr.utils.ErrCode" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sp" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@include file="../base_path.jsp" %>

<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="description" content="">

    <link rel="stylesheet" type="text/css" href="<%=basePath%>/lib/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen"
          href="<%=basePath%>/lib/jqgrid/5.2.1/css/ui.jqgrid-bootstrap.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/lib/lobibox/css/lobibox.min.css"/>
    <link type="text/css" rel="stylesheet" href="<%=basePath%>/lib/bootstrap-select/css/bootstrap-select.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/css/mycss.css"/>
    <style type="text/css">
        .header-right {
            position: absolute;
            right: 0px;
            top: 0px;
            bottom: inherit;
        }

        .col-xs-2 {
            width: 11%;
        }

        #form_filter .control-label {
            float: left;
        }
    </style>
    <title>任务详细</title>

</head>
<body>
<div class="navbar-fixed-top">
    <div class="breadcrumb">
        <span>呼入中心</span>/
        <span>数据报表</span>/
        <%--<span><a href="<%=basePath%>/task/showTaskManager.do">任务管理</a></span>/--%>
        <span class="active">队列报表</span>
        <span class="pull-right" title="刷新">
           <div class="btn-refresh" onclick="location.replace(location.href);">
           	<img src="<%=basePath%>/images/refresh.png" >
           </div>
        </span>

    </div>
</div>

<div class="container-fluid" style="margin-top: 40px;">
    <div class="container-fluid-main">
        <div class="page-header">
            <h3>队列报表</h3>

        </div>

        <div class="panel-group" id="accordion">
            <div class="panel panel-default panel-default-sample">
                <div class="panel-body">
                    <form class="form-horizontal" role="form" id="form_filter">

                        <div class="col-xs-2">
                            <input type="text" class="form-control input-sm Wdate" id="begin_date" autocomplete="off"
                                   disableautocomplete  placeholder="开始时间"
                                   onclick="var end_date=$dp.$('end_date');WdatePicker({isShowClear:false,
                                   onpicked:function(dq){var myobj=isCleanEndDate(dq.cal.getNewDateStr(),end_date.value);
                                   if(!myobj.ispass){end_date.value=myobj.maxDay;}},
                                       errDealMode:1,dateFmt: 'yyyy-MM-dd', maxDate:'%y-%M-%d'})">
                        </div>
                        <label class="control-label" style="padding-left: 0;">至</label>
                        <div class="col-xs-2">
                            <input type="text" class="form-control input-sm Wdate" id="end_date" autocomplete="off"
                                   disableautocomplete  placeholder="结束时间"
                                   onclick="var begin_date=$dp.$('begin_date');var begin_datestr=begin_date.value;if(isEmpty(begin_datestr)){
                                        bootbox.alert('请先选择开始日期');return false;}
                                       WdatePicker({isShowClear:false,errDealMode:1,dateFmt: 'yyyy-MM-dd',
                                       minDate:'#F{$dp.$D(\'begin_date\')}', maxDate:'#F{getMaxDay($dp.$D(\'begin_date\'))}'})">
                        </div>




                        <div class="col-xs-2">
                            <input type="text" class="form-control input-sm" id="txt_value"
                                   name="txt_value"
                                   placeholder="请输入队列名称">
                        </div>
                        <div class="col-xs-2">
                            <button class="btn btn-primary btn-sm" id="btn_query" type="button">查询</button>
                        </div>

                        <div class="col-xs-2" style="float: right">
                            <button class="btn btn-primary btn-sm" id="btn_export" type="button">导出</button>
                        </div>

                    </form>
                </div>
            </div>
        </div>

        <table id="callInInfoJQGrid"></table>
        <div style="height: 40px" id="callInInfoJQGridPager"></div>
    </div>
</div>

<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:1200px;">
        <div class="modal-content" style="width:1200px;">

        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/jquery/1.11.0/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap/3.3.7/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootbox/bootbox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/My97DatePicker/4.8/WdatePicker.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/lobibox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/messageboxes.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/notifications.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/bootstrap-select.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/wavesurfer.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/wavesurfer.regions.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>
<!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript">
    var arr_dialog_info, call_info, curRowData;
    var waveSurfer;
    var lastCallId, nextCallId, call_id
    var $table = "#callInInfoJQGrid";
    $(function () {
        $("#begin_date").val(getLastMonth());
        $("#end_date").val(getToday());
        $('#select_business').selectpicker();
        var createNotify = null;
        $.jgrid.defaults.responsive = true;
        $.jgrid.defaults.styleUI = "Bootstrap";
        var $callInInfoJQGrid = $("#callInInfoJQGrid").jqGrid({
            height: 434,
            autowidth:true,
            autoScroll: false,
            width:'100%',
            shrinkToFit: true, /*  autoScroll: false, *//*forceFit: true, */
            colNames: ["主键", "队列名称", "坐席数量", "进线量", "接听量", "未接听量",  "接听率",
                "排队放弃量",  "总通话时长(s)", "平均通话时长(s)"],
            colModel: [
                {name: "id", index: "id", key: true, hidden: true},
                {name: "queueName", index: "queueName",width: "100%",autowidth: true, align: "left"},
                {name: "seatNumberCount", index: "seatNumberCount",width:"100%", autowidth: true,align: "left"},
                {name: "incomingLine", index: "incomingLine", align: "left",width: "100%", },
                {name: "listening", index: "call_time",width: "100%", align: "left", },
                {name: "noListening", index: "noListening",width: "100%", align: "left", },

                {name: "listeningRate", index: "listeningRate", width: "100%",autowidth: true, align: "left"},
                {name: "queueGiveUpCount", index: "queueGiveUpCount",width: "100%", align: "left"},
                {name: "billsec", index: "billsec", autowidth: true, align: "left"},
                {name: "avgBillsec", index: "avgBillsec",autowidth: true, align: "left"},
            ],
            pager: "#callInInfoJQGridPager",
            viewrecords: true,
            sortable: true,
            sortname: 'duration',
            hidegrid: false,
            multiselect: false,
            url: "<%=basePath%>/ivrReportForms/queueList.do",
            postData: getJQGridFilterData(),
            datatype: 'json',
            rownumbers: true,
            rownumWidth: 100,
            rowNum: 30,
            rowList: [15, 30, 50],
            jsonReader: {
                root: "dataList", page: "currPage", total: "totalPages",          //   很重要 定义了 后台分页参数的名字。
                records: "totalCount", repeatitems: false, id: "id"
            },
            loadComplete: function (data) {
                // 自动调整高度
                var resCount = data.records;
                var tableHeight = resCount * 30 + 40;
                $("#gbox_callInInfoJQGrid .ui-jqgrid-bdiv").css(
                    "cssText",
                    "height: " + tableHeight + "px!important;");
            },
            gridComplete: function () {         // 数据加载完成后 添加 采购按钮
                $("#callInInfoJQGrid").jqGrid('setLabel', 'rn', '序号', {'text-align': 'center', 'font-size': '12px'}, '');

            },
            beforeSelectRow: function (rowid, e) {
                // var $myGrid = $(this),
                //     i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                //     cm = $myGrid.jqGrid('getGridParam', 'colModel');
                // return (cm[i].name != 'opt');
            },
            onSelectRow: function (rowid) {

            },
            ondblClickRow: function (id) {
                <%--$("#modalCallInfo").modal({--%>
                <%--remote: '<%=basePath %>/call/callInfoShow.do?reserve_id=' + id--%>
                <%--});--%>
//                if (id && id !== lastSel) {
//                    jQuery('#blacklistJQGrid').jqGrid('restoreRow', lastSel);
//                    jQuery('#blacklistJQGrid').jqGrid('editRow', id, true);
//                    lastSel = id;
//                }
            }

        });




        $("#btn_export").click(function () {
            var data = $("#callInInfoJQGrid").jqGrid('getRowData');
            console.log(data)
            if (data.length == 0) {
                myNotify("warning", "", "暂无数据可导出！");
            } else {

                window.location.href = "<%=basePath%>/ivrReportForms/downLoadQueueListExcel.do?"+
                    "&startTime=" + getJQGridFilterData().startTime + "&endTime=" + getJQGridFilterData().endTime
                    + "&queueName=" + getJQGridFilterData().queueName;
            }
        });
        // $('body').on('hidden.bs.modal', '.modal', function () {
        //     console.log('111111111')
        //     // destroyWave();
        // });
        //
        // $("#btnPlayPauseFullAudio").click(function () {
        //     waveSurfer.playPause();
        // });

        /**
         * 保存人工校验结果
         */




    });
    $("#btn_query").click(function () {
        refreshJQGrid();
    });
    /******************************方法声明**********************************/
    /**
     * 刷新表格数据
     */
    function refreshJQGrid() {
        $("#callInInfoJQGrid").jqGrid("setGridParam", {
            url: "<%=basePath%>/ivrReportForms/queueList.do",
            mtype: 'POST',
            datatype: "json",
            postData: getJQGridFilterData(),
            page: 1
        }).trigger("reloadGrid");
    }

    // 获取筛选数据
    function getJQGridFilterData() {
        var postData = {};
        postData.queueName= $('#txt_value').val();
        //开始时间
        postData.startTime = $('#begin_date').val();
        //结束时间
        postData.endTime = $('#end_date').val();
        return postData;
    }

    //获取上一条或下一条id
    function getLastNextCallId(id) {
        var data = getJQGridFilterData();
        data.callId = id;
        //curRowData = jQuery("#callInInfoJQGrid").jqGrid('getRowData', callId);
        $.ajax({
            url: "<%=basePath%>/call/getLastNextCallId.do",
            data: data,
            async: false,
            dataType: "json",
            success: function (data) {
                console.log(data)
                if (data["errorCode"] == "0") {
                    lastCallId = data.map.lastCallId;
                    nextCallId = data.map.nextCallId;
                    $('#lastAudio').prop('disabled', false);
                    $('#nextAudio').prop('disabled', false);
                    if (!lastCallId) {
                        $('#lastAudio').prop('disabled', true);
                    }

                    if (!nextCallId) {
                        $('#nextAudio').prop('disabled', true);
                    }
                }
            },
            error: function (data) {

            }
        });
    }

    //播放上一条或下一条信息  index: 1播放上一条 2播放下一条
    function playLastNextCallInfo(index) {
        if (checkContentChange()) {
            myNotify("warning", "", "内容已修改请先保存后再进行操作！", "");
            return false
        }
        destroyWave()
        var targetCallId = lastCallId;
        if (index == 2) {
            targetCallId = nextCallId;
        }
        $.ajax({
            url: "<%=basePath%>/call/getCallDialogueInfo.do",
            data: "callId=" + targetCallId,
            async: true,
            dataType: "json",
            success: function (data) {
                console.log(data)
                if (data["errorCode"] == "0") {
                    curRowData = {
                        answer_time: dateFormat(data["callInfo"].answerTime),
                        phone_number: data["callInfo"].phoneInfo.phoneNumber
                    }
                    call_info = data["callInfo"];
                    arr_dialog_info = data["callDialogueInfoList"];
                    showDialogInfo();
                }
            },
            error: function (data) {

            }
        });
        getLastNextCallId(targetCallId)
    }


    // 导出单个数据
    function exportSingleData(call_id) {
        window.location.href = "<%=basePath%>/dialog/exportSingleAudioData.do?call_id=" + call_id;
    }

    // 导出语音/全部 数据校验
    function checkExportAudioData(exportUrl) {
        $.ajax({
            url: '<%=basePath%>/call/incoming/checkIncomingCallsAudioData.do',
            data: getJQGridFilterData(),
            async: false,
            dataType: 'json',
            success: function (data) {
                if (data["errorCode"] == "0") {
                    exportData(exportUrl)
                } else {
                    bootbox.confirm({
                        message: "导出语音数据一共" + data["object"] + "条，是否继续导出？",
                        buttons: {
                            confirm: {
                                label: '是',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '否',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                exportData(exportUrl);
                            }
                        }
                    });

                }
            },
            error: function (data) {

            }
        });
    }

    function exportData(url) {
        window.location.href = url + "?business_id=" + getJQGridFilterData().business_id +
            "&call_begin_time=" + getJQGridFilterData().beginTime + "&call_end_time=" + getJQGridFilterData().endTime +
            "&result=" + getJQGridFilterData().result + "&like_phone=" + getJQGridFilterData().likePhoneNumber + "&case_type=" + getJQGridFilterData().case_type +
            "&min_duration=" + getJQGridFilterData().minDuration + "&max_duration=" + getJQGridFilterData().maxDuration;
        return false;
    }

    function showCallDialogInfo(callId) {
        call_id = callId
        $("#myModal").modal({
            backdrop: 'static',     // 点击空白不关
            keyboard: false,        // 按键盘esc也不会关闭
            remote: '<%=basePath %>/call/showCallDialog.do'
        })
    }

    /**
     *
     * @returns {boolean} true： 内容有改 false：内容没改
     */
    function checkContentChange() {
        var mcResult = $("#select_manual_check_result").find("option:selected").val().trim();
        var mcComment = $("#txt_manual_check_comment").val().trim();
        return call_info.manualCheckResult != mcResult
            || (call_info.manualCheckComment != null && call_info.manualCheckComment != mcComment)
            || (call_info.manualCheckComment == null && mcComment != "");
    }

    function showDialogInfo1() {
        waveSurfer.on("ready", function () {
            $("#audio_progress").attr("aria-valuenow", 100);
            $("#audio_progress").css("width", '100%');
            $("#audio_progress").text('100%');
            $("#btnPlayPauseFullAudio").removeAttr('disabled');
            waveSurfer.play();
        });
        waveSurfer.on('loading', function (progress) {
            console.log(progress);
            $("#audio_progress").attr("aria-valuenow", progress);
            $("#audio_progress").css("width", progress + '%');
            $("#audio_progress").text(progress + '%');
        });
        waveSurfer.load("<%=basePath%>/call/playAudioFull.do?callId=" + call_info.id);

        $("#div_answer_time").text("接听时间：" + curRowData.answer_time);
        $("#div_call_number").text("外呼号码：" + curRowData.phone_number);
        $("#div_result").html("营销结果：" + getCallResultContentByKey(call_info.result));
        $("#select_manual_check_result option[value='" + call_info.manualCheckResult + "']").prop("selected", true);
        $("#txt_manual_check_comment").val(call_info.manualCheckComment);
        var content = "";
        for (var i = 0; i < arr_dialog_info.length; ++i) {
            var dialogInfo = arr_dialog_info[i];
            if (dialogInfo.channel == 0) {
                content += "<div class='direct-chat-msg right'>" +
                    "<div class='direct-chat-info clearfix'>" +
                    "<span class='direct-chat-name pull-right'>用户</span>" +
                    "<span class='direct-chat-timestamp pull-left'>" + dateFormat(dialogInfo.dialogTime) + "</span></div>" +
                    "<img class='direct-chat-img' src='<%=basePath%>/images/user.png'><div class='direct-chat-text'>" +
                    dialogInfo.content.replace("<", "&lt;").replace(">", "&gt;") + "</div></div>";
                //replace("<","&lt;").replace(">","&gt;")
            } else if (dialogInfo.channel == 1) {
                content += "<div class='direct-chat-msg left'>" +
                    "<div class='direct-chat-info clearfix'>" +
                    "<span class='direct-chat-name pull-left'>机器人</span>" +
                    "<span class='direct-chat-timestamp pull-right'>" + dateFormat(dialogInfo.dialogTime) + "</span></div>" +
                    "<img class='direct-chat-img' src='<%=basePath%>/images/robot.jpg'><div class='direct-chat-text'>" +
                    dialogInfo.content.replace("<", "&lt;").replace(">", "&gt;") + "</div></div>";
            }
        }
        $("#dialog_info").html(content);
        $("#modal_call_dialogue_info").modal({
            backdrop: 'static',     // 点击空白不关
            keyboard: false,        // 按键盘esc也不会关闭
            <%--remote: '<%=basePath %>/call/showCallDialogueInfo.do?callId=' + callId--%>
        });
    }

    function getCallResultContentByKey(code) {
        <c:forEach var="item" items="${marketResultList}">
        var resultCode = "${item.resultCode}";
        if (resultCode == code) {
            return "${item.htmlContent}";
        }
        </c:forEach>
    }

    function getCallManualCheckResultContentByKey(code, successTypeName) {
        <c:forEach var="item" items="${manualCheckResultList}">
        var resultCode = "${item.resultCode}";
        if (resultCode == code) {
            if (code == 1) {
                var content = "${item.htmlContent}";
                if (successTypeName != "") {
                    return content.replace("${item.resultName}", "${item.resultName}-" + successTypeName);
                } else {
                    return content;
                }

            } else {
                return "${item.htmlContent}";
            }

        }
        </c:forEach>
    }

    function getCallAnswerStatusContentByCode(code) {
        <c:forEach var="item" items="${callAnswerStatusList}">
        var statusCode = "${item.statusCode}";
        if (statusCode == code) {
            return "${item.htmlContent}";
        }
        </c:forEach>
    }

    function getCallStatusHtmlContent(code) {
        var statusHtml = "";
        if (code == 1) {
            statusHtml = "<span class='label label-info'>待呼叫</span>";
        } else if (code == 2) {
            statusHtml = "<span class='label label-success'>呼叫中</span>";
        } else if (code == 3) {
            statusHtml = "<span class='label label-primary'>已完成</span>";
        } else if (code == 4) {
            statusHtml = "<span class='label label-warning'>已暂停</span>";
        } else if (code == 5) {
            statusHtml = "<span class='label label-danger'>已终止</span>";
        } else if (code == 6) {
            statusHtml = "<span class='label label-danger'>超时</span>";
        } else if (code == 7) {
            statusHtml = "<span class='label label-default'>黑名单</span>";
        }
        return statusHtml;
    }

    function getCallCaseTypeHtmlContent(code) {
        <c:forEach var="item" items="${callCaseTypeList}">
        var statusCode = "${item.typeCode}";
        if (statusCode == code) {
            return "${item.htmlContent}";
        }
        </c:forEach>
        return "--";
    }

    function getCallMarkStatusHtmlContent(code) {
        <c:forEach var="item" items="${callMarkStatusList}">
        var statusCode = "${item.statusCode}";
        if (statusCode == code) {
            return "${item.statusName}";
        }
        </c:forEach>
    }

    function destroyWave() {
        $("#audio_progress").attr("aria-valuenow", 0);
        $("#audio_progress").css("width", '0%');
        $("#audio_progress").text('0%');
        $("#btnPlayPauseFullAudio").attr('disabled', true);
        waveSurfer.stop();
        waveSurfer.un('ready');
        waveSurfer.un('loading');
        $(this).removeData('bs.modal');
    }
    function beginDateClickRefreshTaskData() {
    }
</script>
</body>
</html>